package td.pt.other;

import td.domain.TagDef;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;

public class TagTreeModel implements TreeViewModel {

	SingleSelectionModel<TagDef> selectionModel;
	private ListDataProvider<TagDef> rootDataProvider;

	public TagTreeModel(SingleSelectionModel<TagDef> selectionModel) {
		this.selectionModel = selectionModel;
	}

	/**
	 * Get the {@link NodeInfo} that provides the children of the specified
	 * value.
	 */
	public <T> NodeInfo<?> getNodeInfo(T value) {
		// Root level
		if (value instanceof TagDef) {
			TagDef tag = (TagDef) value;
			if (tag.getChildren() == null) {
				return null;
			}
			ListDataProvider<TagDef> dataProvider = new ListDataProvider<TagDef>(
					tag.getChildren());
			if (tag.getParent() == null) {
				this.rootDataProvider = dataProvider;
			}

			return new DefaultNodeInfo<TagDef>(dataProvider, cell, selectionModel,
					null);
		}
		return null;
	}

	public void refresh() {
		this.rootDataProvider.refresh();
	}

	/**
	 * Check if the specified value represents a leaf node. Leaf nodes cannot be
	 * opened.
	 */
	public boolean isLeaf(Object value) {
		if (value instanceof TagDef) {
			TagDef category = (TagDef) value;
			return category.getChildren() == null;
		}
		return true;
	} // Create a cell to display a composer.

	public Cell<TagDef> cell = new AbstractCell<TagDef>() {
		@Override
		public void render(Context context, TagDef tag, SafeHtmlBuilder sb) {
			if (tag != null) {
				sb.appendHtmlConstant("<b>")
						.appendEscaped(tag.getName())
						.appendHtmlConstant("</b><br/>")
						.appendEscaped(
								"Thoughts: " + tag.getNumThoughts()
										+ ", Reads: " + tag.getNumReads());
			}
		}
	};
}